package com.fish.config;

import com.fish.consts.SqlType;
import com.fish.pojo.Configuration;
import com.fish.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        //获取命名空间
        String namesapce = rootElement.attributeValue("namespace");

        //获取sql语句标签
        String[] sqlTypeList = SqlType.getAll();
        for (String sqlType : sqlTypeList) {
            List<Element> list = rootElement.selectNodes("//" + sqlType);
            list.forEach(element -> {
                //获取mapper属性
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String paramterType = element.attributeValue("paramterType");
                String sqlText = element.getTextTrim();

                //封装到mappedStatement
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setSql(sqlText);
                mappedStatement.setSqlType(sqlType);

                //把mapper放入configuration
                String key = namesapce + "." + id;
                configuration.getMappedStatementMap().put(key, mappedStatement);
            });
        }
    }
}
